package com.hcc.gateway.app.filter;

import com.hcc.gateway.app.constant.HccGatewayAppConstant;
import com.hcc.gateway.common.utils.JsonUtils;
import com.hcc.gateway.domain.resp.GatewayResp;
import com.hcc.gateway.netty.context.GatewayExchange;
import com.hcc.gateway.netty.context.RespContext;
import com.hcc.gateway.netty.filter.GatewayFilter;
import com.hcc.gateway.netty.filter.GatewayFilterChain;
import com.hcc.gateway.netty.support.ByteBufUtils;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpResponseStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * ResponseFilter
 *
 * @author shengjun.hu
 * @date 2021/12/27
 */
@Slf4j
@Component
public class WriteResponseFilter implements GatewayFilter {

    @Override
    public int getOrder() {
        return 400;
    }

    @Override
    public void filter(GatewayExchange exchange, GatewayFilterChain chain) {
        log.info("进入ResponseFilter !");

        RespContext respContext = exchange.getRespContext();

        Object respResult = exchange.getAttributeByName(HccGatewayAppConstant.HCC_RESP_RESULT);
        if (respResult instanceof byte[]) {
            respContext.setHttpStatus(HttpResponseStatus.OK);
            respContext.setBody(ByteBufUtils.writeByteToByteBuf((byte[]) respResult));
            return;
        }

        String traceId = exchange.getAttributeByName(HccGatewayAppConstant.HCC_TRACE_ID, String.class);
        GatewayResp<Object> resp = new GatewayResp<>();
        resp.setTraceId(traceId);
        resp.setCode("GW200");
        resp.setMsg("success");
        resp.setSuccess(true);
        resp.setTimestamp(System.currentTimeMillis());
        resp.setData(respResult);

        respContext.getHeaders().set(HttpHeaderNames.CONTENT_TYPE, "application/json;charset=UTF-8");
        respContext.setHttpStatus(HttpResponseStatus.OK);
        String json = JsonUtils.writeValueAsString(resp);
        respContext.setBody(ByteBufUtils.writeStringToByteBuf(json));
    }

}
